// pages/refill-success/refill-success.js
Page({
	data: {
		patientName: '',
		prescriptionId: '',
		refillTime: '',
		deliveryType: 'self', // self: 自取, home: 配送
		deliveryTypeText: '',
		campus: '',
		medicineCost: '',
		totalCost: '',
		beforeBalance: '',
		afterBalance: ''
	},

	onLoad(options) {
		console.log('配药成功页面加载')
		console.log('页面参数:', options)
		
		// 获取当前时间
		const now = new Date()
		const refillTime = this.formatDateTime(now)
		
		// 模拟用户余额（实际项目中应从后端获取）
		const beforeBalance = 500.00
		const totalCost = parseFloat(options.totalCost || '37.20')
		const afterBalance = beforeBalance - totalCost
		
		const data = {
			refillTime: refillTime,
			medicineCost: options.medicineCost || '37.20',
			totalCost: options.totalCost || '37.20',
			beforeBalance: beforeBalance.toFixed(2),
			afterBalance: afterBalance.toFixed(2)
		}
		
		if (options.patient) {
			data.patientName = options.patient
		}
		
		if (options.prescriptionId) {
			data.prescriptionId = options.prescriptionId
		}
		
		if (options.deliveryType) {
			data.deliveryType = options.deliveryType
			data.deliveryTypeText = options.deliveryType === 'self' ? '到院自取' : '送药上门'
		} else {
			data.deliveryTypeText = '到院自取'
		}
		
		if (options.campus) {
			data.campus = options.campus
		} else {
			data.campus = '湘南院区'
		}
		
		this.setData(data)
		
		// 保存余额变动到本地存储（模拟）
		this.saveBalanceChange(beforeBalance, totalCost, afterBalance)
	},

	// 格式化日期时间
	formatDateTime(date) {
		const year = date.getFullYear()
		const month = String(date.getMonth() + 1).padStart(2, '0')
		const day = String(date.getDate()).padStart(2, '0')
		const hour = String(date.getHours()).padStart(2, '0')
		const minute = String(date.getMinutes()).padStart(2, '0')
		
		return `${year}-${month}-${day} ${hour}:${minute}`
	},

	// 保存余额变动记录
	saveBalanceChange(beforeBalance, deductionAmount, afterBalance) {
		try {
			// 获取现有的余额变动记录
			let balanceHistory = wx.getStorageSync('balanceHistory') || []
			
			// 添加新的变动记录
			const newRecord = {
				id: Date.now().toString(),
				type: 'deduction', // 扣减
				reason: '在线配药',
				amount: deductionAmount,
				beforeBalance: beforeBalance,
				afterBalance: afterBalance,
				time: this.data.refillTime,
				prescriptionId: this.data.prescriptionId,
				patientName: this.data.patientName
			}
			
			balanceHistory.unshift(newRecord)
			
			// 只保留最近50条记录
			if (balanceHistory.length > 50) {
				balanceHistory = balanceHistory.slice(0, 50)
			}
			
			// 保存到本地存储
			wx.setStorageSync('balanceHistory', balanceHistory)
			wx.setStorageSync('currentBalance', afterBalance)
			
			console.log('余额变动记录已保存:', newRecord)
		} catch (error) {
			console.error('保存余额变动记录失败:', error)
		}
	},

	// 查看订单
	viewOrder() {
		console.log('查看订单')
		wx.navigateTo({
			url: '/pages/order-detail/order-detail?patient=' + this.data.patientName + 
				'&prescriptionId=' + this.data.prescriptionId + 
				'&deliveryType=' + this.data.deliveryType + 
				'&medicineCost=' + this.data.medicineCost + 
				'&totalCost=' + this.data.totalCost + 
				'&campus=' + this.data.campus
		})
	},

	// 返回首页
	backToHome() {
		console.log('返回首页')
		wx.reLaunch({
			url: '/pages/index/index'
		})
	}
})
